﻿using Nop.Core.Domain.Media;
using Nop.Core.Infrastructure;
using Nop.Services.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Nop.Admin
{
    public class BlobStartupTask : IStartupTask
    {
        public void Execute()
        {
            var physicalPath = HttpRuntime.AppDomainAppPath;
            physicalPath += @"\subsites\commerce\Content\Images";
            var mediaSettings = DependencyResolver.Current.GetService<MediaSettings>();
            var blobConnectionString = mediaSettings.BlobStorageConnectionString;
            var productImageContainer = mediaSettings.ProductImageContainer;
            var client = BlobStorageHelper.GetBlobClient(blobConnectionString);
            var container = BlobStorageHelper.GetContainer(client, productImageContainer);

            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                if (Directory.Exists(physicalPath))
                {
                    var files = Directory.GetFiles(physicalPath);
                    foreach (var file in files)
                    {
                        BlobStorageHelper.CopyLocalFileToBlobStorage(container,
                            File.ReadAllBytes(file), Path.GetFileName(file));
                    }
                }
            });

            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                var thumbPath = physicalPath + @"\Thumbs";
                if (Directory.Exists(thumbPath))
                {
                    var files = Directory.GetFiles(thumbPath);
                    foreach (var file in files)
                    {
                        BlobStorageHelper.CopyLocalFileToBlobStorage(container,
                            File.ReadAllBytes(file), Path.GetFileName(file), "Thumbs");
                    }
                }
            });

        }

        

        public int Order
        {
            get { return 0; }
        }
    }
}